package com.guoxue.action.front;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.guoxue.consts.SCUser;
import com.guoxue.dataClasses.SimpleData;
import com.guoxue.domain.DistrictVo;
import com.guoxue.domain.UserVo;
import com.guoxue.service.IDistrictService;
import com.guoxue.service.IUserService;
import com.guoxue.util.LoggerUtil;
import com.guoxue.util.OSSUtil;
import com.guoxue.util.OtherUtils;
import com.guoxue.util.PasswordUtil;
import com.guoxue.util.RedisUtil;
import com.guoxue.util.codeSwitch.khb;
import com.guoxue.util.codeSwitch.zt;

import redis.clients.jedis.Jedis;

@Controller
@RequestMapping("User")
/**
 * 用户账户信息处理接口
 * 主要包括：
 * 1-1.bindAccount绑定第三方账号
 * 1-2.cancelAccount解绑第三方账号
 * 2.bindTel为账户绑定手机
 * 3.modifyPersionSignature修改个性签名
 * 4.modifySex修改角色性别
 * 5.modifyNickName修改角色名称
 * 6.changePass根据旧密码修改密码
 * 7.modifypassword根据手机短信验证找回密码
 * 8.modifyTel解绑手机并绑定新手机
 * 9.modifyDistrict绑定用户所在区域信息
 * @author kanghb
 */
public class AccountAction extends BaseAction{
	@Resource
	private IUserService userService;
	@Resource
	private IDistrictService districtService;
	
	
	/**
	 * 绑定用户账号
	 * 
	 * @param req
	 * @param resp
	 * @param uid
	 *            用户id
	 * @param type
	 *            1.新浪账号2.微信账号3.QQ账号
	 * @param account
	 *            用户新的账号
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/bindAccount")
	public JSON bindAccount(HttpServletRequest req, HttpServletResponse resp, Integer uid, Integer type,
			String account) {
		zt.ts.function(); // 绑定第三方账号时,需要对第三方账号进行检查?

		try {
			if (null == uid) {
				return Message(ERROR, "未提交用户id", null);
			}
			if (null == type) {
				return Message(ERROR, "未提交账号类型", null);
			}
			if (isEmpty(account)) {
				return Message(ERROR, "未提交账号", null);
			}
			// 1.新浪账号2.微信账号3.QQ账号
			if (type > 3 || type < 1) {
				return Message(ERROR, "账号类型错误", null);
			}
			UserVo user = userService.getUserByKey(uid);
			if (null == user) {
				return Message(ERROR, "账号不存在", null);
			} else {
				UserVo entiy = null;
				if (type == 1) {
					entiy = userService.getUser(account, 4);
				}
				if (type == 2) {
					entiy = userService.getUser(account, 3);
				}
				if (type == 3) {
					entiy = userService.getUser(account, 2);
				}
				if (entiy != null) {
					return Message(ERROR, "该第三放账号已被绑定", null);
				}
				if (type == 1) {
					String isNull = user.getSinaAccount();
					if (!isEmpty(isNull)) {
						return Message(ERROR, "您已经绑定了新浪账号,不能再进行绑定", null);
					}
					user.setStatus(1);
					user.setSinaAccount(account);
				} else if (type == 2) {
					String isNull = user.getWechatAccount();
					if (!isEmpty(isNull)) {
						return Message(ERROR, "您已经绑定了微信账号,不能再进行绑定", null);
					}
					user.setStatus(1);
					user.setWechatAccount(account);
				} else if (type == 3) {
					String isNull = user.getQqAccount();
					if (!isEmpty(isNull)) {
						return Message(ERROR, "您已经绑定了QQ账号,不能再进行绑定", null);
					}
					user.setStatus(1);
					user.setQqAccount(account);
				}
				userService.saveUser(user);
				return Message(SUCCESS, "绑定用户账号成功", null);
			}
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "绑定用户账号失败");
		}
	}
	/**
	 * 解绑非手机号 第三方授权
	 * @param req
	 * @param resp
	 * @param type
	 * 		解绑类型 1：qq 2：微信 3：新浪
	 * @param uid
	 * @return
	 */
	@RequestMapping("cancelAccount")
	@ResponseBody
	public JSON cancelAccount(HttpServletRequest req, HttpServletResponse resp,Integer type,Integer uid){
		if (uid==null){
			return Message(ERROR, "未提交用户id", null);
		}
		if (type==null||type>3){
			return Message(ERROR, "未指定类型", null);
		}
		UserVo user = userService.getUserByKey(uid);
		if (user==null){
			return Message(ERROR, "当前用户不存在", null);
		}
		int c =0;
		if (!isEmpty(user.getQqAccount())){
			c = c+1;
		}
		if (!isEmpty(user.getSinaAccount())){
			c = c+1;
		}
		if (!isEmpty(user.getUserTel())){
			c = c+1;
		}
		if (!isEmpty(user.getWechatAccount())){
			c = c+1;
		}
		if (c<=1){
			return Message(ERROR, "当前账户只有一种绑定方式,请添加其他方式后再解绑", null);
		}
		if (type==1){
			user.setQqAccount("");
		}
		if (type==2){
			user.setWechatAccount("");
		}
		if (type==3){
			user.setSinaAccount("");
		}
		userService.saveUser(user);
		return Message(SUCCESS, "解绑成功", null);
	}
	
	/**
	 * 绑定手机号
	 * @param req
	 * @param resp
	 * @param tel
	 * 			绑定的电话号码
	 * @param pass
	 * 			密码
	 * @param messageCode
	 * 			验证码
	 * @param uid
	 * 			用户id
	 * @return
	 */
	@RequestMapping("/bindTel")
	@ResponseBody
	public JSON A1_bindTel(HttpServletRequest req, HttpServletResponse resp, String tel, String pass,
			String messageCode) {
		final int uid = SCUser.getUidFromReq(req);
		final String redisCodeKey, redisCodeValue;
		final SimpleData sd;

		zt.ts.function(); // 此接口除了绑定手机号码,还同时修改了用户登录密码?(参数"pass"及其相关操作是多余的!?)
		// 参数基本检查:
		if (isEmpty(messageCode)) {
			return Message(ERROR, "验证码错误", null);
		}
		if (isEmpty(tel)) {
			return Message(ERROR, "未提交电话号码", null);
		}
		if (!OtherUtils.isMobileNO(tel)) {
			return Message(ERROR, "请正确输入电话号码", null);
		}
		zt.ta.function(); // 检查密码格式合法性
		if (isEmpty(pass)) {
			return Message(ERROR, "密码不能为空", null);
		}
		redisCodeKey = SendMessageAction.getSmsRedisKey(uid, tel,
				102/* 绑定手机号操作,type等于102! */);

		Jedis jedis = RedisUtil.getJedis();
		try {
			// 检查验证码:
			redisCodeValue = jedis.get(redisCodeKey);
			sd = SendMessageAction.parseSmsRedisValue(redisCodeValue);
			// String code = jedis.get("message" + tel);
			if (sd == null) {
				return Message(ERROR, "验证码已过期，时效10分钟", null);
			}
			if (!messageCode.equals(sd.name)) {
				return Message(ERROR, "验证码错误，请核对后输入", null);
			}
			// 检查用户自身是否已绑定了手机号:
			UserVo userVo_uid = userService.getUserByKey(uid);
			if (!isEmpty(userVo_uid.getUserTel())) {
				if (userVo_uid.getUserTel().equals(tel)) {
					jedis.del(redisCodeKey);
					zt.tc.optimize(); // 优化用户提示
					return Message(SUCCESS, "您已绑定了该手机号码", null);
				} else {
					jedis.del(redisCodeKey);
					zt.tc.optimize(); // 提示用户可以修改绑定的手机号码
					return Message(ERROR, "您已绑定了其它手机号码", null);
				}
			}
			// 检查要绑定的手机号码,是否已被其它账号绑定:
			zt.ta.function(); // 加集群锁,锁定要绑定的手机号码!
			{
				UserVo userVo_tel = userService.getUserByTel(tel);
				if (userVo_tel != null) {
					jedis.del(redisCodeKey);
					return Message(ERROR, "该手机号已被其它账号绑定了", null);
				}
				// 至此,通过了所有检查,开始修改用户绑定的手机号码:
				userVo_uid.setUserTel(tel);
				zt.ta.question(); // 同时修改用户密码?
				userVo_uid.setUserPassword(pass);
				userVo_uid = PasswordUtil.passwordGenerator(userVo_uid);
				userService.saveUser(userVo_uid); // 必须立即存入数据库,以保证锁内检查有效!
			} // end 加集群锁,锁定要绑定的手机号码!

			jedis.del(redisCodeKey);
			return Message(SUCCESS, "绑定成功", null);
		} catch (Exception e) {
			LoggerUtil.logInfo(e, "绑定异常");
		}finally {
			RedisUtil.returnResource(jedis);
		}
		return null;
	}
	
	/**
	 * 修改个性签名
	 * @param req
	 * @param resp
	 * @param signature
	 * 			签名
	 * @param uid
	 * 			用户id
	 * @return
	 */
	@RequestMapping("/modifyPersionSignature")
	@ResponseBody
	public JSON modifyPersionSignature(HttpServletRequest req, HttpServletResponse resp,String signature, Integer uid){
		if (isEmpty(signature)){
			return Message(SUCCESS, "签名修改成功", null);
		}
		if(OtherUtils.getWordCount(signature)>60){
			return Message(ERROR, "最多输入56个字符哦", null);
		}
		UserVo user = userService.getUserByKey(uid);
		user.setPersonSignature(signature);
		userService.saveUser(user);
		return Message(SUCCESS, "签名修改成功", null);
	}
	
	/**
	 * 修改性别
	 * @param req
	 * @param resp
	 * @param sex
	 * 			性别 1：男 2：女
	 * @param uid
	 * 			用户id
	 * @return 
	 */
	@RequestMapping("/modifySex")
	@ResponseBody
	public JSON modifySex(HttpServletRequest req, HttpServletResponse resp,Integer sex, Integer uid){
		if (uid==null){
			return Message(ERROR, "用户id未提交", null);
		}
		if (sex==null||sex<=0){
			return Message(ERROR, "参数错误", null);
		}
		Jedis jedis = RedisUtil.getJedis();
		try {
			String flag = jedis.get("sex"+uid);
			if (flag!=null&&flag.equals("true")){
				return Message(ERROR, "您已修改过性别", null);
			} else {
				UserVo user = userService.getUserByKey(uid);
				if (user==null){
					return Message(ERROR, "当前用户不存在", null);
				}
				user.setSex(sex);
				userService.saveUser(user);
				jedis.set("sex"+uid, "true");
				return Message(SUCCESS, "修改性别成功", null);
			}
		} catch (Exception e) {
			LoggerUtil.logInfo(e, "修改性别异常");
		}finally {
			jedis.close();
		}
		return null;
	}
	
	/**
	 * 修改用户昵称
	 * @param req
	 * @param resp
	 * @param nickName
	 * 			昵称
	 * @param uid
	 * 			用户id
	 * @return
	 */
	@RequestMapping("/modifyNickName")
	@ResponseBody
	public JSON modifyNickName(HttpServletRequest req, HttpServletResponse resp,String nickName,Integer uid){
		if (uid==null&&isEmpty(nickName)){
			return Message(ERROR, "参数不全", null);
		}
		UserVo user = userService.getUserByKey(uid);
		if (user==null){
			return Message(ERROR, "当前用户不存在", null);
		}
		if (OtherUtils.isNumber(nickName)){
			return Message(ERROR, "名称不能为全数字", null);
		}
		if (OtherUtils.getWordCount(nickName)>20){
			return Message(ERROR, "昵称过长", null);
		}
		UserVo user2 = userService.getUserByNickname(nickName);
		if (user2!=null){
			return Message(ERROR, "当前用户名已存在", null);
		}
		user.setNickName(nickName);
		userService.saveUser(user);
		return Message(SUCCESS, "换新名字咯", nickName);
	}

	/**
	 * 修改密码接口
	 * @param req
	 * @param resp
	 * @param oldPass
	 * 			旧密码
	 * @param newPass
	 * 			新密码
	 * @param uid
	 * 			用户id
	 * @return
	 */
	@RequestMapping("/changePass")
	@ResponseBody
	public JSON changePass(HttpServletRequest req, HttpServletResponse resp, String oldPass,
			String newPass,Integer uid){
		if (uid==null){
			return Message(ERROR, "未提交用户id", null);
		}
		if (isEmpty(oldPass)||isEmpty(newPass)){
			return Message(ERROR, "密码不完整", null);
		}
		UserVo user = userService.getUserByKey(uid);
		if (user==null){
			return Message(ERROR, "未查找到用户", null);
		}
		boolean flag = false;
		flag = PasswordUtil.validPassword(user.getUserPassword(), oldPass, user.getSalt());
		if (flag==false){
			return Message(ERROR, "密码错误", null);
		}
		user.setUserPassword(newPass);
		user = PasswordUtil.passwordGenerator(user);
		userService.saveUser(user);
		return Message(SUCCESS, "修改密码成功", null);
	}
	
	/**
	 * 找回密码
	 * @param req
	 * @param resp
	 * @param tel
	 * 			电话号码
	 * @param modifyCode
	 * 			验证码
	 * @param password
	 * 			新密码
	 * @return
	 */
	@RequestMapping("/modifyPassword")
	@ResponseBody
	public JSON A1_modifypassword(HttpServletRequest req, HttpServletResponse resp, String tel, String modifyCode,
			String password) {
		final int uid = SCUser.getUidFromReq(req);
		final String redisCodeKey, redisCodeValue;
		final SimpleData sd;

		// 参数基本检查:
		zt.tb.function(); // 对password的合法性进行检查
		if (isEmpty(modifyCode) || isEmpty(tel) || isEmpty(password)) {
			return Message(ERROR, BAD_PARAM, null);
		}
		redisCodeKey = SendMessageAction.getSmsRedisKey(uid, tel,
				104/* 修改密码操作,type等于104! */);

		Jedis jedis = RedisUtil.getJedis();
		try {
			// 检查验证码:
			redisCodeValue = jedis.get(redisCodeKey);
			sd = SendMessageAction.parseSmsRedisValue(redisCodeValue);
			if (sd == null) {
				return Message(ERROR, "验证码已失效", null);
			}
			if (!modifyCode.equals(sd.name)) {
				return Message(ERROR, "验证码错误", null);
			}
			// 获取用户账号数据对象,检查手机号码:
			UserVo user = userService.getUserByKey(uid);
			if (user.getUserTel() == null || !user.getUserTel().equals(tel)) {
				return Message(ERROR, "手机号码错误", null);
			}
			// 至此,通过了检查,开始修改密码:
			user.setUserPassword(password);
			user = PasswordUtil.passwordGenerator(user);
			userService.saveUser(user);
			// 删除redis中缓存的验证码:
			jedis.del(redisCodeKey);
			return Message(SUCCESS, "修改成功", null);
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "密码修改失败");
		}finally {
			jedis.close();
		}
	}
	/**
	 * 修改绑定手机
	 * @param req
	 * @param resp
	 * @param tel
	 * 			旧手机号
	 * @param modifyCode
	 * 			验证码
	 * @param newTel
	 * 			新手机号
	 * @return
	 */
	@RequestMapping("/modifyTel")
	@ResponseBody
	public JSON A1_modifyTel(HttpServletRequest req, HttpServletResponse resp, String tel, String modifyCode,
			String newTel) {
		final int uid = SCUser.getUidFromReq(req);
		final String redisCodeKey, redisCodeValue;
		final SimpleData sd;

		// 参数基本检查:
		if (isEmpty(tel)) {
			return Message(ERROR, "未提交修改前号码", null);
		}
		if (isEmpty(newTel)) {
			return Message(ERROR, "未提交新号码", null);
		}
		if (!OtherUtils.isMobileNO(newTel)) {
			return Message(ERROR, "请正确输入电话号码", null);
		}
		if (isEmpty(modifyCode)) {
			return Message(ERROR, "未提交验证码", null);
		}
		redisCodeKey = SendMessageAction.getSmsRedisKey(uid,
				tel/* 注意:验证码发往的是原手机号! */, 103/* 修改绑定的手机号码操作,type等于103! */);

		Jedis jedis = RedisUtil.getJedis();
		try {
			// 检查验证码:
			redisCodeValue = jedis.get(redisCodeKey);
			sd = SendMessageAction.parseSmsRedisValue(redisCodeValue);
			// String code = jedis.get("message" + tel);
			if (sd == null) {
				return Message(ERROR, "验证码已过期，时效10分钟", null);
			}
			if (!modifyCode.equals(sd.name)) {
				return Message(ERROR, "验证码错误，请核对后输入", null);
			}
			// 检查用户自身是否已绑定了手机号:
			UserVo userVo_uid = userService.getUserByKey(uid);
			if (isEmpty(userVo_uid.getUserTel()) || tel.equals(userVo_uid.getUserTel()) == false) {
				if (userVo_uid.getUserTel().equals(newTel)) {
					jedis.del(redisCodeKey);
					zt.tc.optimize(); // 优化用户提示
					return Message(SUCCESS, "您已绑定了该手机号码", null);
				} else {
					return Message(SUCCESS, "原手机号码错误", null);
				}
			}

			// 检查要绑定的手机号码,是否已被其它账号绑定:
			zt.ta.function(); // 加集群锁,锁定要绑定的手机号码!
			{
				UserVo userVo_tel = userService.getUserByTel(newTel);
				if (userVo_tel != null) {
					jedis.del(redisCodeKey);
					return Message(ERROR, "该手机号已被其它账号绑定了", null);
				}
				// 至此,通过了所有检查,开始修改用户绑定的手机号码:
				userVo_uid.setUserTel(newTel);
				userService.saveUser(userVo_uid); // 必须立即存入数据库,以保证锁内检查有效!
			} // end 加集群锁,锁定要绑定的手机号码!

			jedis.del(redisCodeKey);
			return Message(SUCCESS, "修改绑定的手机号码成功", null);
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "绑定手机号异常");
		}finally {
			jedis.close();
		}
	}
	/**
	 * 
	 * @param req
	 * @param resp
	 * @param uid
	 * 			用户id
	 * @param district
	 * 			区域
	 * @return
	 */
	@RequestMapping("modifyDistrict")
	@ResponseBody
	public JSON modifyDistrict(HttpServletRequest req, HttpServletResponse resp, Integer uid,String district){
		if (isEmpty(district)){
			return Message(ERROR, "未提交区域信息", null);
		}
		if (uid==null){
			return Message(ERROR, "未提交用户id", null);
		}
		String[] dis = district.split(",");
		String city = "";
		String province = "";
		String county = "";
		String school = "";
		if (dis.length<2||dis.length>4){
			return Message(ERROR, "选择区域失败", null);
		}
		DistrictVo disc = new DistrictVo();
		for (int i =0;i<dis.length;i++){
			if (i==0){
				province = dis[i];
				disc.setProvince(province);
			}
			if (i==1){
				city = dis[i];
				disc.setCity(city);
			}
			if (i==2){
				county = dis[i];
				disc.setCounty(county);
			}
			if (i==3){
				school = dis[i];
				disc.setSchool(school);
			}
		}
		DistrictVo disct = districtService.searchDistrict(dis);
		if (disct==null){
			districtService.saveDistrict(disc);
		}
		disct = districtService.searchDistrict(dis);
		UserVo user = userService.getUserByKey(uid);
		user.setDistrict(disct.getId());
		userService.saveUser(user);
		return Message(SUCCESS, "设置地区成功", null);
	}
	
}
